<template>
  <!-- 返回链接 -->
  <el-link @click="router.push('/home')" :underline="false" class="back-link">
    <el-icon style="vertical-align: middle; font-size: 28px"><ArrowLeft /></el-icon>
    <span style="vertical-align: middle; font-size: 25px">返回</span>
  </el-link>

  <!-- 邮件表单 -->
  <el-form :model="form" label-width="80px" class="main-container">
    <!-- 收件人输入 -->
    <el-form-item label="收件人" :error="receiverError" :class="{ 'is-error': receiverError }">
      <el-input
        v-model="form.receiver"
        @blur="validateReceiver"
        placeholder="请输入收件人ID或邮箱"
      />
    </el-form-item>

    <!-- 抄送输入 -->
    <el-form-item label="抄送">
      <el-input v-model="form.cc" placeholder="多个用逗号分隔" />
    </el-form-item>

    <!-- 主题输入 -->
    <el-form-item label="主题">
      <el-input v-model="form.subject" />
    </el-form-item>

    <!-- 正文输入 -->
    <el-form-item label="正文">
      <el-input type="textarea" v-model="form.content" rows="25" />
    </el-form-item>

    <!-- 附件上传 -->
    <div>
      <input type="file" ref="fileInput" style="margin-right: 12px" />
      <el-button
        type="primary"
        @click="uploadAttach"
        style="background-color: #ff8585; border: none"
        >上传附件</el-button
      >
    </div>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button
        type="primary"
        @click="saveDraft"
        :loading="loading"
        style="background-color: #ccc; border: none"
        >保存草稿</el-button
      >
      <el-button
        type="success"
        @click="sendMail"
        :loading="loading"
        style="background-color: #ff8585; border: none"
        >发送</el-button
      >
    </el-form-item>

    <!-- 附件列表 -->
    <li v-for="attachment in form.attachments" :key="attachment.id">
      <div>
        <span>{{ attachment.file_name }}</span>
        <el-button type="danger" @click="deleteAttachment(attachment.id)">删除</el-button>
      </div>
    </li>
  </el-form>
</template>

<script setup lang="ts">
// ==================== 路由和导入 ====================
// 导入Vue相关功能
import { ref, onBeforeUnmount, onMounted } from 'vue'
// 导入路由相关功能
import { useRouter, useRoute } from 'vue-router'
// 导入邮件相关API
import { createDraftAPI, sendMailAPI } from '@/api/mailsAPI'
// 导入Element Plus组件和消息提示
import { ElMessage } from 'element-plus'
// 导入附件相关类型和API
import { type AttachListItem, deleteAttachmentAPI } from '@/api/attachAPI'
// 导入Element Plus图标
import { ArrowLeft } from '@element-plus/icons-vue'
// 导入基础URL和axios
import { BASEURL } from '@/api/http'
import axios from 'axios'

// 获取路由实例
const router = useRouter()
const route = useRoute()

// ==================== 表单数据 ====================
// 定义表单数据响应式对象
const form = ref({
  receiver: '', // 收件人
  cc: '', // 抄送
  subject: '', // 主题
  content: '', // 正文内容
  attachments: [] as AttachListItem[], // 附件列表
})

// 加载状态，用于按钮的loading效果
const loading = ref(false)
// 标记是否已提交（发送或保存），用于组件卸载时判断是否需要清理附件
let deliver: boolean = false

// ==================== 收件人验证 ====================
// 收件人错误信息
const receiverError = ref('')
// 收件人验证状态
const receiverValid = ref(true)

/**
 * 验证收件人格式
 * 收件人可以是纯ID（字母数字组合）或标准邮箱格式
 */
const validateReceiver = () => {
  const value = form.value.receiver.trim()
  // ID正则：只包含字母数字
  const idReg = /^[a-z0-9]+$/
  // 邮箱正则：简单邮箱格式验证
  const emailReg = /^[a-z0-9]+@[a-z0-9]+\.com$/

  // 验证是否符合任一格式
  receiverValid.value = idReg.test(value) || emailReg.test(value)

  // 设置错误信息
  if (!receiverValid.value) {
    receiverError.value = '请输入正确的收件人ID或邮箱地址'
  } else {
    receiverError.value = ''
  }
}

// ==================== 附件处理 ====================
// 文件输入DOM引用
const fileInput = ref<HTMLInputElement>()

/**
 * 上传附件API
 * @returns 返回附件信息
 */
const uploadAttachmentAPI = async (): Promise<AttachListItem> => {
  // 创建FormData对象用于文件上传
  const formData = new FormData()
  // 获取用户ID和token
  const id = localStorage.getItem('id') || ''
  const token = localStorage.getItem('token') || ''

  // 添加文件和空email_id（因为是新邮件）
  formData.append('file', fileInput.value!.files![0])
  formData.append('email_id', String(''))

  try {
    // 发送上传请求
    const response = await axios.post(BASEURL + '/attach/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data', // 必须设置的内容类型
        id: id, // 用户ID
        token: token, // 认证token
      },
    })

    // 处理响应数据
    if (response.data && response.data.data) {
      ElMessage.success('上传附件成功')
      return response.data.data as AttachListItem
    } else {
      throw new Error('无效的响应数据')
    }
  } catch (error) {
    ElMessage.error('更新草稿失败' + error)
    throw error
  }
}

/**
 * 上传附件按钮点击处理
 */
const uploadAttach = async () => {
  // 检查是否选择了文件
  const file = fileInput.value?.files?.[0]
  if (!file) {
    ElMessage.error('请选择文件')
    return
  }
  // 文件大小限制：500MB
  const maxSize = 500 * 1024 * 1024
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过500MB')
    return
  }

  try {
    // 调用上传API
    const res = await uploadAttachmentAPI()
    if (res) {
      // 上传成功后将附件添加到列表
      form.value.attachments.push(res)
    }
  } catch (e) {
    console.error(e)
  }
}

/**
 * 删除附件
 * @param attachment_id 要删除的附件ID
 */
const deleteAttachment = async (attachment_id: number) => {
  try {
    // 调用删除API
    const res = await deleteAttachmentAPI({ attachment_id })
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 从列表中移除已删除的附件
      form.value.attachments = form.value.attachments.filter((item) => item.id !== attachment_id)
    }
  } catch (e) {
    ElMessage.error('删除附件失败' + e)
    console.log(e)
  }
}

// ==================== 邮件操作 ====================
/**
 * 保存草稿
 */
const saveDraft = async () => {
  loading.value = true // 开始加载
  deliver = true // 标记已提交

  // 验证收件人格式
  validateReceiver()
  if (!receiverValid.value) {
    ElMessage.error('收件人格式不正确，无法保存草稿')
    loading.value = false
    return
  }

  try {
    // 调用保存草稿API
    const res = await createDraftAPI({
      receiver: form.value.receiver,
      // 处理抄送字段，分割、去空格、过滤空值
      cc: form.value.cc
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
      subject: form.value.subject,
      content: form.value.content,
      // 提取附件ID数组
      attachments: form.value.attachments.map((item) => item.id),
      send_now: false, // 不立即发送
    })

    // 处理响应
    if (res.code === 200) {
      ElMessage.success('草稿已保存')
      router.push('/draft') // 跳转到草稿箱
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('保存草稿失败' + e)
  } finally {
    loading.value = false // 结束加载
  }
}

/**
 * 发送邮件
 */
const sendMail = async () => {
  loading.value = true // 开始加载
  deliver = true // 标记已提交

  // 验证收件人格式
  validateReceiver()
  if (!receiverValid.value) {
    ElMessage.error('收件人格式不正确，无法发送')
    loading.value = false
    return
  }

  try {
    // 调用发送邮件API
    const res = await sendMailAPI({
      receiver: form.value.receiver,
      // 处理抄送字段
      cc: form.value.cc
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
      subject: form.value.subject,
      content: form.value.content,
      // 提取附件ID数组
      attachments: form.value.attachments.map((item) => item.id),
    })

    // 处理响应
    if (res.code === 200) {
      ElMessage.success('发送成功')
      router.push('/sent') // 跳转到已发送
    } else {
      ElMessage.error(res.msg)
    }
  } catch (e) {
    ElMessage.error('发送失败' + e)
  } finally {
    loading.value = false // 结束加载
  }
}

// ==================== 组件卸载处理 ====================
/**
 * 组件卸载前的清理工作
 * 如果未提交（未发送或保存），则删除所有已上传的附件
 */
onBeforeUnmount(async () => {
  if (!deliver) {
    // 遍历所有附件并删除
    for (const attachment of form.value.attachments) {
      try {
        await deleteAttachmentAPI({ attachment_id: attachment.id })
      } catch (e) {
        console.log('自动删除附件失败', attachment.id, e)
      }
    }
  }
})

// ==================== 组件挂载处理 ====================
// 组件挂载时的初始化
onMounted(() => {
  // 如果是“写回信”跳转，自动填充
  if (route.query.receiver) {
    form.value.receiver = String(route.query.receiver)
  }
  if (route.query.subject) {
    // 可选：自动加“回复:”前缀
    form.value.subject = '回复: ' + String(route.query.subject)
  }
  if (route.query.originBody) {
    // 构造正文内容
    const detail = [
      `\n\n------- 原邮件 -------`,
      `发件人：${route.query.originSender || ''}`,
      `时间：${route.query.originTime || ''}`,
      `内容：\n${route.query.originBody || ''}`,
      `---------------------\n`,
    ].join('\n')
    form.value.content = detail
  }
})
</script>

<style scoped>
.back-link .el-icon {
  margin-right: 4px;
  font-size: 18px;
  margin-bottom: 20px;
}
.back-link span {
  margin-right: 4px;
  font-size: 18px;
  margin-bottom: 20px;
}
.back-link:hover {
  color: #d16053;
}
</style>
